import {defineStore} from "pinia";
import {ref, computed} from "vue";
import {defaultEngines, defaultCurrentEngine} from "@/stores/default-data.ts";

export interface Engine {
    baseUrl: string,
    description: string,
    enable?: string | null,
    iconBase64?: string,
    id: string,
    name?: string
}

export const useEngineStore = defineStore(
    "engine",
    () => {

        const currentEngine = ref(defaultCurrentEngine);
        const engines = ref<Engine[]>([...defaultEngines]);


        function addEngine(payload: Engine) {
            if (payload) {
                engines.value.push(payload);
            }
        }

        function deleteEngine(engineId: string) {
            const index = engines.value.findIndex((item) => item.id === engineId);
            if (index !== -1) {
                engines.value.splice(index, 1);
            }
        }

        function updateCurrentEngine(payload: string) {
            if (payload) {
                currentEngine.value = payload;
            }
        }

        function setDefaultEngine() {
            if (engines.value.length > 0) {
                currentEngine.value = engines.value[0].description;
            } else {
                currentEngine.value = "百度";
            }
        }

        function clear() {
            engines.value.splice(0, engines.value.length);
        }

        function setEngines(payload: Engine[]) {
            if (Array.isArray(payload)) {
                engines.value = [...payload];
                setDefaultEngine();
            }
        }

        return {
            currentEngine,
            engines,
            addEngine,
            deleteEngine,
            updateCurrentEngine,
            setDefaultEngine,
            clear,
            setEngines,
        };
    },
    {
        persist: {
            key: 'engine',
            storage: localStorage
        },
    }
);
